package com.mrper.ui.main;

import android.view.View;
import android.widget.AdapterView;

import com.etsy.android.grid.StaggeredGridView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.miguo.activity.callback.IGoodsScroll;
import com.miguo.activity.callback.listener.GoodsScrollListener;
import com.miguo.app.AppHelper;
import com.miguo.bean.GoodsBean;
import com.miguo.framework.request.FailData;
import com.miguo.framework.request.JsonData;
import com.miguo.framework.utils.Toast;
import com.miguo.framework.view.pulltorefresh.PullToRefreshBase;
import com.miguo.http.HttpClient;
import com.miguo.http.Url;
import com.miguo.ui.R;
import com.miguo.ui.databinding.FragmentDoubleNineListcontentBinding;
import com.mrper.ext.adapter.goods.Double9Adapter;
import com.mrper.ext.annotation.ContentView;
import com.mrper.ext.uibase.BasicFragment;
import com.mrper.model.type.Double9Type;
import com.mrper.util.AnimationUtil;
import com.mrper.util.TimeUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2016/3/11.
 * 九块九列表片段
 */
@SuppressWarnings("all")
@ContentView(R.layout.fragment_double_nine_listcontent)
public class FragmentDoubleNineListContent extends BasicFragment<FragmentDoubleNineListcontentBinding>
        implements PullToRefreshBase.OnRefreshListenerTwo<StaggeredGridView>,View.OnClickListener,AdapterView.OnItemClickListener,IGoodsScroll {

    public static final String TAG = FragmentDoubleNineListContent.class.getSimpleName();

    private Double9Adapter adapter;//数据适配器
    private int currentPage = 0,pageCount = 0,lastVisibleItemIndex = 0;//当前页码,上一次可见的列表项索引
    private Double9Type type = Double9Type.NEW;//类型ID 默认显示全部 1:九块商品 2:十九块 3:二十九块 5:四十九块

    /**
     * 构造函数
     * @param type 9块9类型
     */
    public FragmentDoubleNineListContent(Double9Type type){
        this.type = type;
    }

    @Override
    protected void initViews() {
        super.initViews();
        dataBinder.setOnClickEvent(this);
        dataBinder.stateView.setContentView(dataBinder.flCOntainer);
        dataBinder.stateView.getRefreshView().setOnClickListener(this);
        dataBinder.stateView.getNetworkView().setOnClickListener(this);
    }

    @Override
    protected void onActivityLoadFinished() {
        super.onActivityLoadFinished();
        adapter = new Double9Adapter(context);
        dataBinder.lvGoods.setAdapter(adapter);
        dataBinder.lvGoods.setOnRefreshListener(this);
        dataBinder.lvGoods.setOnItemClickListener(this);
        dataBinder.lvGoods.setOnScrollListener(new GoodsScrollListener(this));
    }

    @Override
    protected void doDataLoad() {
        super.doDataLoad();
        loadGoodsData();//加载商品数据
    }

    @Override
    protected boolean isInitHttpCallback() { return false; }

    @Override
    public boolean isInitShowLoadingDialog() { return true; }

    /**  控件点击事件  **/
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.refresh_rl://刷新事件
            case R.id.network_error_ll://网络错误事件
                loadGoodsData();//加载商品数据
                break;
            case R.id.img2Top://去顶部
                dataBinder.lvGoods.smoothScroll2Top();
                onScrollTopPositiont();//执行滚动到顶部隐藏的动画
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        GoodsBean item = (GoodsBean)dataBinder.lvGoods.getItemAtPosition(position);
        AppHelper.startGoodsDetailPage(activity,item);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
        currentPage = 0;//页码默认为0
        loadGoodsData();//加载商品数据
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
        if(currentPage + 1>pageCount){
            Toast.show(context, "已经到底了!");
            dataBinder.lvGoods.onRefreshComplete();
            return;
        }
        loadGoodsData();//加载商品数据
    }

    @Override
    public void onScrollIdle() {
        imageLoader.resume();
    }

    @Override
    public void onScrollFling() {
        imageLoader.pause();
    }

    @Override
    public void onScrollTouchScroll() {
        imageLoader.pause();
    }

    @Override
    public void onScrollTopPositiont() {
        // 判断滚动到顶部
        if (dataBinder.img2Top.getVisibility() == View.VISIBLE) {
            dataBinder.img2Top.setVisibility(View.GONE);
            dataBinder.img2Top.startAnimation(AnimationUtil.getGo2TopButton2HideAnimation());
        }
    }

    @Override
    public void onScrollFirstLastPosition() {
        onScrollLastPosition();
        // 第一次滚动至底部
//        if (dataBinder.img2Top.getVisibility() == View.GONE) {
//            dataBinder.img2Top.setVisibility(View.VISIBLE);
//            dataBinder.img2Top.startAnimation(AnimationUtil.getGo2TopButton2ShowAnimation());
//        }
    }

    @Override
    public void onScrollLastPosition() {
        // 判断滚动到底部
        if (dataBinder.img2Top.getVisibility() == View.GONE) {
            dataBinder.img2Top.setVisibility(View.VISIBLE);
            dataBinder.img2Top.startAnimation(AnimationUtil.getGo2TopButton2ShowAnimation());
        }
        if(currentPage + 1 <= pageCount){
            loadGoodsData();//加载商品数据
        }else {
//            Toast.show(context, "已经到底了!");
            dataBinder.lvGoods.onRefreshComplete();
        }
    }

    @Override
    public void onResume() {
        if(adapter!=null)//刷新页面数据
            adapter.notifyDataSetChanged();
        super.onResume();
    }

    /** 加载商品数据 **/
    private void loadGoodsData(){
        Map<String,String> params = new HashMap<>();
        if(type.getValue() != 0) //默认显示全部 1:九块商品 2:十九块 3:二十九块 5:四十九块
            params.put("cid",String.valueOf(type.getValue()));
//        params.put("show_type",String.valueOf(0)); //为空默认显示全部 显示类型 0:全部 1:当日新品
        params.put("page",String.valueOf(++currentPage));
        HttpClient.post(Url.toRoute(Url.ExtUrl.DoubleNine, 1), params,httpCallback);
    }

    @Override
    public void onLoadHttpDataSuccessful(JsonData json) {
        super.onLoadHttpDataSuccessful(json);
        dataBinder.lvGoods.onRefreshComplete();
        if (json.optInt("status") == 200) {
            JsonData json_data = json.optJson("data");
            try {
                String updateTime = "";//更新时间
                JsonData json_page = json_data.optJson("page");
                currentPage = json_page.optInt("page");
                pageCount = json_page.optInt("page_size");
                if(json_data.has("update_time")){//设置更新时间
                    long time = Long.parseLong(json_data.optString("update_time"));
                    updateTime = TimeUtil.getTimeDescription(time);
                }
                //设置页面数据
                List<GoodsBean> goods = new Gson().fromJson(
                        json_data.optJson("item").toString(),
                        new TypeToken<ArrayList<GoodsBean>>() {}.getType()
                );
                if (goods != null && goods.size() > 0) {
                    if(currentPage == 1) {//重置加载，清空数据
                        adapter.clear();
                        adapter.addItem(new GoodsBean(updateTime));//添加一项更新时间数据
                    }
                    adapter.addItem(goods);
                    adapter.syncDataSource();
                }
                dataBinder.stateView.setRefreshVisibility(View.GONE);
                return;
            }catch (Exception e){
                e.printStackTrace();
            }
            currentPage--;
            Toast.show(context, getResources().getString(R.string.pull_to_refresh_nodata));
        } else {
            currentPage--;
            Toast.show(context, json.optString("info"));
        }
        dataBinder.stateView.setRefreshVisibility(View.VISIBLE);
    }

    @Override
    public void onLoadHttpDataFaield(FailData data) {
        super.onLoadHttpDataFaield(data);
        dataBinder.lvGoods.onRefreshComplete();
        if(currentPage > 0) currentPage--; //页码最小不能小于0，大于0的情况下，如果未加载成功，页面需要还原
        dataBinder.stateView.setRefreshVisibility(View.VISIBLE);
    }

}
